package cn.sdormitory.controller;

import cn.sdormitory.basedata.entity.BDormitory;
import cn.sdormitory.basedata.service.BDormitoryService;
import cn.sdormitory.basedata.vo.BStudentAppHyInfoVo;
import cn.sdormitory.basedata.vo.BStudentAppHyVo;
import cn.sdormitory.common.annotation.IgnoreAuth;
import cn.sdormitory.common.annotation.SysLog;
import cn.sdormitory.common.api.CommonResult;
import cn.sdormitory.common.api.UploadResult;
import cn.sdormitory.common.constant.CommonConstant;
import cn.sdormitory.common.dto.ResultMsg;
import cn.sdormitory.common.enums.BusinessType;
import cn.sdormitory.service.*;
import cn.sdormitory.smartdor.entity.HygieneDeduct;
import cn.sdormitory.smartdor.entity.SdHygiene;
import cn.sdormitory.smartdor.entity.SdHygieneItemRecord;
import cn.sdormitory.smartdor.entity.SdHygieneStudent;
import cn.sdormitory.smartdor.service.SdManualHygieneService;
import cn.sdormitory.smartdor.service.SdStudentHygieneService;
import cn.sdormitory.smartdor.vo.SdHygieneVo;
import cn.sdormitory.smartdor.vo.SdStudentHygieneVo;
import cn.sdormitory.sys.entity.SysDictDetail;
import cn.sdormitory.sys.entity.SysUser;
import cn.sdormitory.sysset.entity.SyssetHygieneDeduct;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @创建人：zhouyang
 * @创建时间：2021/1/8 15:13
 * @version：V1.0
 */
@RestController
@RequestMapping("/app/Hygiene")
@Api("APP端卫生管理接口")
public class AppHygieneController {
    @Autowired
    private AppHygieneService appHygieneService;
    @Autowired
    private AppDictDetailService appDictDetailService;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private SdManualHygieneService sdManualHygieneService;
    @Autowired
    private BDormitoryService bDormitoryService;
    @Autowired
    private AppStudentService appStudentService;
    @Autowired
    private SdStudentHygieneService sdStudentHygieneService;
    @Autowired
    AppSdHygieneItemRecordService appSdHygieneItemRecordService;

    @ApiOperation(value = "APP端宿舍卫生列表")
    @GetMapping("/getHygieneAll")
    public ResultMsg getHygieneAll(String checkDate,String storey,String buildingNo) {
        List<SdHygieneVo> sdHygieneList=appHygieneService.getHygieneAll(checkDate,storey,buildingNo);
        return  ResultMsg.BY_SUCCESS("获取成功",sdHygieneList);
    }

    @ApiOperation(value = "APP端获取每个宿舍整体卫生状况")
    @GetMapping("/getHygieneByDor")
    public ResultMsg getHygieneByDor(Long bdormitoryId,String checkDate) {
        SdHygieneVo sdHygiene=appHygieneService.getAppHygieneByBIdAndDate(bdormitoryId,checkDate);
        return  ResultMsg.BY_SUCCESS("获取成功",sdHygiene);
    }

    @ApiOperation("getAppStuHyListByDId => APP端卫生考核查询某宿舍对应学员信息列表")
    @GetMapping(value = "/getAppStuHyListByDId")
    public ResultMsg listDorAttence(Long dormitoryId,String checkDate){
        int count=appStudentService.getAppBStuHyCount(dormitoryId,checkDate);
        List<BStudentAppHyVo> studentVoList=new ArrayList<>();
        if(count>0){
            studentVoList=appStudentService.getAppBStuHyByDormitoryId(dormitoryId,checkDate);
        }else{
            studentVoList=appStudentService.getAppBStuHyByDormitoryIdNo(dormitoryId);
        }
        return ResultMsg.BY_SUCCESS("获取成功",studentVoList);
    }

    @ApiOperation("getAppStuHyInfoById => APP端查询某学员详细信息及当天卫生考核情况")
    @GetMapping(value = "/getAppStuHyInfoById")
    public ResultMsg getAppStuHyInfoById(String studentNo,String checkDate){
        int count=appStudentService.getAppBStudentCountById(studentNo,checkDate);
        List<BStudentAppHyInfoVo> studentVoList=new ArrayList<>();
        if(count>0){
            studentVoList=appStudentService.getAppStuHyInfoById(studentNo,checkDate);
        }else{
            studentVoList=appStudentService.getAppStuHyInfoByIdNo(studentNo);
        }
        return ResultMsg.BY_SUCCESS("获取成功",studentVoList);
    }

    @ApiOperation(value="APP端新增卫生考核(不带图片)")
    @PostMapping(value = "/createHygiene")
    public CommonResult<Integer> create(@RequestBody SdHygiene sdHygiene) throws IOException {
        //根据宿舍ID查询宿舍号
        BDormitory bDormitory=bDormitoryService.getBDormitoryById(sdHygiene.getBdormitoryId());
        sdHygiene.setDormitoryNo(bDormitory.getDormitoryNo());
        sdHygiene.setBuildingNo(bDormitory.getBuildingNo());
        sdHygiene.setStorey(bDormitory.getStorey());
        int count = sdManualHygieneService.create(sdHygiene);

        if (count >0 ){
            List<SdHygieneItemRecord> hygieneItemRecordList = sdHygiene.getHygieneItemRecordList();
            List<SdHygieneItemRecord> insertList = new ArrayList<>();
            for(SdHygieneItemRecord item : hygieneItemRecordList){
                item.setBdormitoryId(sdHygiene.getBdormitoryId());
                item.setBuildingNo(bDormitory.getBuildingNo());
                item.setStorey(bDormitory.getStorey());
                item.setDormitoryNo(bDormitory.getDormitoryNo());
                item.setCheckDate(sdHygiene.getCheckDate());
                insertList.add(item);
            }
            appSdHygieneItemRecordService.createBatch(insertList);
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    /**
     * 获取图片
     *
     * @param id
     * @param width
     * @param height
     * @param response
     * @throws IOException
     */
    @IgnoreAuth
    @ApiOperation("/getPhoto.do => 获取卫生考核照片")
    @GetMapping("/getPhoto.do")
    public void getPhotoById(Long id, int width, int height, final HttpServletResponse response) throws IOException {
        SdHygiene sdHygiene = sdManualHygieneService.getSdHygieneById(id);
        byte[] data = sdHygiene.getPhoto();
        if (width != 0 && height != 0) {
            data = scaleImage(data, width, height);
        }
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputSream = response.getOutputStream();
        InputStream in = new ByteArrayInputStream(data);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf, 0, 1024)) != -1) {
            outputSream.write(buf, 0, len);
        }
        outputSream.close();
    }
    /**
     * 显示图片
     *
     * @param data   byet流
     * @param width  图片的宽度
     * @param height 图片的高度
     * @return 2020.11.19
     * @throws IOException
     */
    public static byte[] scaleImage(byte[] data, int width, int height) throws IOException {
        BufferedImage buffered_oldImage = ImageIO.read(new ByteArrayInputStream(data));
        int imageOldWidth = buffered_oldImage.getWidth();
        int imageOldHeight = buffered_oldImage.getHeight();
        double scale_x = (double) width / imageOldWidth;
        double scale_y = (double) height / imageOldHeight;
        double scale_xy = Math.min(scale_x, scale_y);
        int imageNewWidth = (int) (imageOldWidth * scale_xy);
        int imageNewHeight = (int) (imageOldHeight * scale_xy);
        BufferedImage buffered_newImage = new BufferedImage(imageNewWidth, imageNewHeight, BufferedImage.TYPE_INT_RGB);
        buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth, imageNewHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);
        buffered_newImage.getGraphics().dispose();
        ByteArrayOutputStream outPutStream = new ByteArrayOutputStream();
        ImageIO.write(buffered_newImage, "jpeg", outPutStream);
        return outPutStream.toByteArray();
    }

    /**
     * 文件上传（表单和文件同步上传）
     *
     * @returncreate
     */
    @ApiOperation("createHygieneUpload => APP端新建卫生考核(带图片)")
    @PostMapping(value = "/createHygieneUpload")
    public CommonResult saveHygiene(@RequestParam(value = "upload") MultipartFile upload, SdHygiene sdHygiene) {
        byte[] pictureData = null;
        // 使用输入流获取上传的图片
        InputStream inputStream = null;
        try {
            inputStream = upload.getInputStream();
            // 定义字节数组用于存放图片信息
            pictureData = new byte[(int) upload.getSize()];
            // 读取图片到字节数组中
            inputStream.read(pictureData);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sdHygiene.setPhoto(pictureData);
        //根据宿舍ID查询宿舍号
        BDormitory bDormitory=bDormitoryService.getBDormitoryById(sdHygiene.getBdormitoryId());
        sdHygiene.setDormitoryNo(bDormitory.getDormitoryNo());
        sdHygiene.setBuildingNo(bDormitory.getBuildingNo());
        sdHygiene.setStorey(bDormitory.getStorey());
        int count = sdManualHygieneService.create(sdHygiene);
        if (count >0 ){
            CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("APP端修改卫生考核信息(不带图片)")
    @PutMapping(value = "/updateHygiene")
    public CommonResult<Integer> update(@RequestBody SdHygiene sdHygiene) {
        BDormitory bDormitory = bDormitoryService.getBDormitoryById(sdHygiene.getBdormitoryId());
        int count = sdManualHygieneService.update(sdHygiene.getId(),sdHygiene);
        if (count > 0) {
            appSdHygieneItemRecordService.deleteBatch(sdHygiene.getBdormitoryId(),sdHygiene.getCheckDate());
            List<SdHygieneItemRecord> hygieneItemRecordList = sdHygiene.getHygieneItemRecordList();
            List<SdHygieneItemRecord> insertList = new ArrayList<>();
            for(SdHygieneItemRecord item : hygieneItemRecordList){
                item.setBdormitoryId(sdHygiene.getBdormitoryId());
                item.setBuildingNo(bDormitory.getBuildingNo());
                item.setStorey(bDormitory.getStorey());
                item.setDormitoryNo(bDormitory.getDormitoryNo());
                item.setCheckDate(sdHygiene.getCheckDate());
                insertList.add(item);
            }
            appSdHygieneItemRecordService.createBatch(insertList);
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("APP端修改卫生考核信息(包含文件上传)")
    @PostMapping (value = "/updateHygieneUpload")
    public CommonResult<Integer> updateAndUpload(@RequestParam(value = "upload") MultipartFile upload, SdHygiene sdHygiene) {
        byte[] pictureData = null;
        // 使用输入流获取上传的图片
        InputStream inputStream = null;
        try {
            inputStream = upload.getInputStream();
            // 定义字节数组用于存放图片信息
            pictureData = new byte[(int) upload.getSize()];
            // 读取图片到字节数组中
            inputStream.read(pictureData);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sdHygiene.setPhoto(pictureData);
        //根据宿舍ID查询宿舍号
        BDormitory bDormitory=bDormitoryService.getBDormitoryById(sdHygiene.getBdormitoryId());
        sdHygiene.setDormitoryNo(bDormitory.getDormitoryNo());
        sdHygiene.setBuildingNo(bDormitory.getBuildingNo());
        sdHygiene.setStorey(bDormitory.getStorey());
        int count = sdManualHygieneService.update(sdHygiene.getId(),sdHygiene);
        if (count >0 ){
            CommonResult.success(count);
        }
        return CommonResult.failed();
    }


    //上传卫生检查照片
    @PostMapping("/upload")
    public UploadResult upload(MultipartFile photo, HttpServletRequest request) throws IOException {
        InputStream inputStream=photo.getInputStream();
        byte[] iconData=new byte[(int)photo.getSize()];
        inputStream.read(iconData);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        UploadResult result = new UploadResult();

        //获取文件上传地址的真实路径
        String realPath =request.getSession().getServletContext().getRealPath("/uploadFile/");
        System.out.println("---------- "+request.getSession().getServletContext()
                .getRealPath("/"));
        String format = sdf.format(new Date());
        //构建文件对象
        File folder = new File(realPath+format);
        if(!folder.isDirectory()){ // 判断目录是否存在
            folder.mkdirs();  // 创建目录
        }
        // 获取上传文件的逻辑名称
        String oldName = photo.getOriginalFilename();
        // 给文件重命名，避免文件重名
        String newName = UUID.randomUUID().toString()+oldName
                .substring(oldName.lastIndexOf("."),oldName.length());
        try{
            // 上传文件至指定的目录
            photo.transferTo(new File(folder,newName));
            //获取文件上传后的完整地址
            String filePath = request.getScheme()+"://"+
                    request.getServerName()+":"+request.getServerPort()+""+request.getContextPath()+
                    "/uploadFile/"+format+newName;
            System.out.println("filePath:"+filePath);
            result.setSuccess(true);
            result.setMessage(filePath);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return result;
    }


//    //获取宿舍栋号/楼层
//    @ApiOperation(value = "宿舍栋号/楼层列表")
//    @GetMapping("/getDorInfo")
//    public ResultMsg getDorInfo(String dictType){
//        List<SysDictDetail> sysDictDetails = appDictDetailService.selectDictDataByType(dictType);
//        if(sysDictDetails != null && sysDictDetails.size()>0){
//            return ResultMsg.BY_SUCCESS("查询宿舍栋号/楼层列表成功", sysDictDetails);
//        }else{
//            return ResultMsg.BY_FAIL("查询宿舍栋号/楼层失败");
//        }
//    }
//
//    //根据栋号+楼层获取宿舍号
//    @ApiOperation(value = "根据栋号+楼层获取宿舍号")
//    @GetMapping("/getBDormitoryListByCol")
//    public ResultMsg getBDormitoryListByCol(String buildingNo,String storey){
//        List<BDormitory> bDormitoryList = appHygieneService.getBDormitoryListByCol(buildingNo,storey);
//        if(bDormitoryList != null && bDormitoryList.size()>0){
//            return ResultMsg.BY_SUCCESS("获取成功", bDormitoryList);
//        }else{
//            return ResultMsg.BY_FAIL("获取失败");
//        }
//    }
//
//    @ApiOperation("getHyDeAll => 获取所有有效卫生扣分项列表")
//    @GetMapping(value = "/getHyDeAll")
//    public ResultMsg getHyDeAll() {
//        List<SyssetHygieneDeduct> bClassList = appHygieneService.getHyDeListAll();
//        return ResultMsg.BY_SUCCESS("获取有效卫生扣分项列表成功", bClassList);
//    }
//
//    @ApiOperation("addHygiene => 卫生检查录入")
//    @PostMapping(value = "/addHygiene")
//    public ResultMsg addHygiene(@RequestBody SdHygiene sdHygiene) {
//        SdHygiene dbSdHygieneInfo = appHygieneService.getByCheckDateAndBdId(sdHygiene.getCheckDate(),sdHygiene.getBdormitoryId());
//        if (dbSdHygieneInfo != null && !Objects.equals(dbSdHygieneInfo.getId(), sdHygiene.getId())) {
//            return ResultMsg.BY_ERROR("该卫生检查已录入!!!",-1);
//        }
//        System.out.println("---------userId-------  "+sdHygiene.getCreateById());
//        SysUser sysUser=appUserService.getUserById(sdHygiene.getCreateById().intValue());
//        sdHygiene.setCreateBy(sysUser.getUsername());
//        //根据宿舍ID查询宿舍号
//        BDormitory bDormitory=appHygieneService.getBDormitoryById(sdHygiene.getBdormitoryId());
//        sdHygiene.setDormitoryNo(bDormitory.getDormitoryNo());
//        int count=0;
//        if(sdHygiene.getDeductIds()!=null) {
//            int deductIdsCount = sdHygiene.getDeductIds().size();
//            double pdeduct = 0;
//            double totalPdeduct = 0;
//            if (deductIdsCount > 0) {
//                List<Long> deductIds = sdHygiene.getDeductIds();
//                for (Long deductId : deductIds) {
//                    pdeduct = appHygieneService.getSyssetHygieneDeductById(deductId).getDeductValue();
//                    totalPdeduct += pdeduct;
//                }
//                sdHygiene.setTotalPdeduct(totalPdeduct);
//                sdHygiene.setTotalScore(CommonConstant.TOTALSCORE_VALUE - totalPdeduct);
//                count = appHygieneService.insertSdHygieneAndDeduct(sdHygiene);
//            } else {
//                sdHygiene.setTotalPdeduct(CommonConstant.TOTALPDEDUCT_VALUE);
//                sdHygiene.setTotalScore(CommonConstant.TOTALSCORE_VALUE);
//                count = appHygieneService.create(sdHygiene);
//            }
//        }
//        if (count > 0) {
//            return ResultMsg.BY_SUCCESS("卫生检查录入成功", count);
//        }
//        return ResultMsg.BY_FAIL("卫生检查录入失败");
//    }
//
//    @ApiOperation("editHygiene => 卫生检查修改")
//    @PostMapping(value = "/editHygiene")
//    public ResultMsg editHygiene(@RequestBody SdHygiene sdHygiene) {
//        SdHygiene dbSdHygieneInfo = appHygieneService.getByCheckDateAndBdId(sdHygiene.getCheckDate(),sdHygiene.getBdormitoryId());
//        if (dbSdHygieneInfo != null && !Objects.equals(dbSdHygieneInfo.getId(), sdHygiene.getId())) {
//            return ResultMsg.BY_ERROR("该卫生检查已录入!!!",-1);
//        }
//        int count = 0;
//        if(sdHygiene.getDeductIds()!=null) {
//            int deductIdsCount = sdHygiene.getDeductIds().size();
//            double pdeduct = 0;
//            double totalPdeduct = 0;
//            if (deductIdsCount > 0) {
//                List<Long> deductIds = sdHygiene.getDeductIds();
//                for (Long deductId : deductIds) {
//                    pdeduct = appHygieneService.getSyssetHygieneDeductById(deductId).getDeductValue();
//                    totalPdeduct += pdeduct;
//                }
//                sdHygiene.setTotalPdeduct(totalPdeduct);
//                sdHygiene.setTotalScore(CommonConstant.TOTALSCORE_VALUE - totalPdeduct);
//            } else {
//                sdHygiene.setTotalPdeduct(CommonConstant.TOTALPDEDUCT_VALUE);
//                sdHygiene.setTotalScore(CommonConstant.TOTALSCORE_VALUE);
//            }
//            count = appHygieneService.updateSdHygieneAndDeduct(sdHygiene);
//        }
//        if (count > 0) {
//            return ResultMsg.BY_SUCCESS("卫生检查修改成功", count);
//        }
//        return ResultMsg.BY_FAIL("卫生检查修改失败");
//    }
//
//    //根据ID获取卫生检查详情
//    @ApiOperation(value = "卫生检查详情")
//    @GetMapping("/getHygieneById")
//    public ResultMsg getHygieneById(Long id){
//        SdHygiene sdHygiene = appHygieneService.getAppHygieneById(id);
//        String deOptions=appHygieneService.getDeOptionsById(id);
//        if(!"".equals(deOptions) && deOptions != null){
//            sdHygiene.setDeductOptions(deOptions);
//            //获取对应的卫生项列表
//            List<Long> deductIdList = appHygieneService.listDeductIdByHygieneId(id);
//            if(deductIdList!=null && deductIdList.size()>0){
//                sdHygiene.setDeductIds(deductIdList);
//            }
//        }
//
//        if(sdHygiene != null){
//            return ResultMsg.BY_SUCCESS("查询卫生检查详情成功", sdHygiene);
//        }else{
//            return ResultMsg.BY_FAIL("查询卫生检查详情失败");
//        }
//    }
//
//    //根据ID删除卫生检查信息
//    @ApiOperation(value = "根据ID删除卫生检查信息")
//    @GetMapping("/deleteHygieneById")
//    public ResultMsg deleteHygieneById(Long id){
//        int result=appHygieneService.delete(id);
//        if (result > 0) {
//            return ResultMsg.BY_SUCCESS("卫生检查删除成功", result);
//        }
//        return ResultMsg.BY_FAIL("卫生检查删除失败");
//    }


    @ApiOperation(value="APP端新增个人卫生考核")
    @PostMapping(value = "/createStuHygiene")
    public CommonResult<Integer> createStuHygiene(@RequestBody SdHygieneStudent sdHygieneStudent) throws IOException {
        //根据宿舍ID查询宿舍号
        BDormitory bDormitory=bDormitoryService.getBDormitoryById(sdHygieneStudent.getBdormitoryId());
        sdHygieneStudent.setDormitoryNo(bDormitory.getDormitoryNo());
        sdHygieneStudent.setBuildingNo(bDormitory.getBuildingNo());
        sdHygieneStudent.setStorey(bDormitory.getStorey());
        int count = sdStudentHygieneService.create(sdHygieneStudent);
        if (count >0 ){
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("APP端修改个人卫生考核信息")
    @PutMapping(value = "/updateStuHygiene")
    public CommonResult<Integer> updateStuHygiene(@RequestBody SdHygieneStudent sdHygieneStudent) {
        int count = sdStudentHygieneService.update(sdHygieneStudent);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }


    @ApiOperation("createUpdateStuHygienes => 新增/修改学生卫生考核信息")
    @PostMapping(value = "/createUpdateStuHygienes")
    public CommonResult<Integer> createUpdateStuHygienes(@RequestBody SdStudentHygieneVo sdStudentHygieneVo) throws IOException {
        int count = sdStudentHygieneService.addStudentHygiene(sdStudentHygieneVo);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();

    }

    @ApiOperation("getStuByCheckDateAndBdormitoryId=>根据卫生检查日期和宿舍ID查询学生信息")
    @GetMapping("/getStuByCheckDateAndBdormitoryId")
    public CommonResult<List<SdStudentHygieneVo>> getStuByCheckDateAndBdormitoryId(String checkDate, String bdormitoryId) {
        List<SdStudentHygieneVo> studentList = sdStudentHygieneService.getStuByCheckDateAndBdormitoryId(checkDate,Long.parseLong(bdormitoryId));
        return CommonResult.success(studentList);
    }
}
